package com.dreamstations.changshads.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.dreamstations.changshads.R;
import com.dreamstations.changshads.activity.ArticleDetailActivity;
import com.dreamstations.changshads.activity.ArticleDetail_WebActivity;
import com.dreamstations.changshads.adapter.DSRvAdapter;
import com.dreamstations.changshads.entity.BaseBean;
import com.dreamstations.changshads.util.DSRequest;
import com.dreamstations.changshads.util.DSUtils;
import com.dreamstations.changshads.util.RequestType;
import com.dreamstations.changshads.view.Slide_Indicator;
import com.squareup.picasso.Picasso;
import com.zhy.base.adapter.ViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 7YHong on 2016/6/27.
 */
public class Topic_Header_Frag extends Topic_Simple_Frag {
    private List<ImageView> headerImageViews = new ArrayList<>();
    private List<String> headerTitles = new ArrayList<>();
    private ViewPager headerPager;
    private Slide_Indicator headerIndicator;
    private TextView headerTitle;

    private int tryAgainTime=0;

    private DSRequest.DSCallback<List<BaseBean>> dsCallback = new DSRequest.DSCallback<List<BaseBean>>() {
        @Override
        public void onResponse(List<BaseBean> result) {
            Picasso picasso = Picasso.with(getActivity());
            headerTitles.clear();
            headerImageViews.clear();
            for (final BaseBean data : result) {
                headerTitles.add(data.getTitle());

                ImageView imageView = new ImageView(getActivity());
                // 异步加载图片
                picasso.load(DSRequest.SERVER_BASE1 + data.getCover())
                        .error(R.drawable.home_nav_header)
                        .into(imageView);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        if (data.getTemplate() == 1) {
                            intent.setClass(getActivity(), ArticleDetail_WebActivity.class);
                        } else {
                            intent.setClass(getActivity(), ArticleDetailActivity.class);
                        }
                        intent.putExtra("data", data);
                        startActivity(intent);
                    }
                });
                headerImageViews.add(imageView);
            }   //赋值完毕
            PagerAdapter pagerAdapter = new PagerAdapter() {
                @Override
                public int getCount() {
                    return headerImageViews.size();
                }

                @Override
                public boolean isViewFromObject(View view, Object object) {
                    return view == object;
                }

                @Override
                public Object instantiateItem(ViewGroup container, int position) {
                    container.addView(headerImageViews.get(position));
                    return headerImageViews.get(position);
                }

                @Override
                public void destroyItem(ViewGroup container, int position, Object object) {
                    container.removeView(headerImageViews.get(position));
                }
            };
            if (headerPager==null) return;
            headerPager.setAdapter(pagerAdapter);
            headerPager.clearOnPageChangeListeners();
            headerIndicator.setupWithViewPager(headerPager);
            headerPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    headerTitle.setText(headerTitles.get(position));
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            headerTitle.setText(headerTitles.get(0));
            tryAgainTime=0;
            if (isFirstIn) {
                isFirstIn = false;
                loadHeaderData(DSUtils.NETWORK_ELSE_CACHED);
            }
        }

        @Override
        public void onFailure(String msg) {
            tryAgainTime++;
            if (tryAgainTime<5)
                loadHeaderData(DSUtils.NETWORK_ELSE_CACHED);
        }
    };

    public Topic_Header_Frag() {
    }

    @SuppressLint("ValidFragment")
    public Topic_Header_Frag(String title, @RequestType String reqType, int category) {
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putString("reqType", reqType);
        bundle.putInt("typeId", category);
        setArguments(bundle);
    }

    @Override
    public DSRvAdapter.RvSupport getHeader() {
        DSRvAdapter.RvSupport header = new DSRvAdapter.RvSupport() {
            @Override
            public int getItemViewType(Object data) {
                return 0;
            }

            @Override
            public ViewHolder createHolder(Context context, ViewGroup parent, int viewType) {
                ViewHolder holder = ViewHolder.get(context, null, parent, R.layout.simple_vpheader, -1);
                headerPager = holder.getView(R.id.header_viewpager);
                headerIndicator = holder.getView(R.id.header_indicator);
                headerTitle = holder.getView(R.id.header_title);

                return holder;
            }

            @Override
            public void convert(ViewHolder holder, Object data) {
            }
        };
        return header;
    }

    private void loadHeaderData(int cacheType){
        DSUtils.getInstance().cancelByTag(Topic_Header_Frag.this);
        //获取Header所需数据
        //noinspection WrongConstant
        new DSRequest()
                .type(getArguments().getString("reqType"))
                //二级分类
                .addParams("page", "1")
                .addParams("typeId", "1")
                .addParams("front", "1")
                .cacheType(cacheType)
                .setTag(Topic_Header_Frag.this)
                .build()
                .execute(dsCallback);
    }

    @Override
    public void onResume() {
        super.onResume();
        int cacheType=DSUtils.NETWORK_ELSE_CACHED;
        if (isFirstIn) cacheType=DSUtils.ONLY_CACHED;
        loadHeaderData(cacheType);
    }

    @Override
    public void onPause() {
        DSUtils.getInstance().cancelByTag(Topic_Header_Frag.this);
        super.onPause();
    }
}
